// DOM元素
const conversionCategoryEl = document.getElementById('conversion-category');
const inputValueEl = document.getElementById('input-value');
const fromUnitEl = document.getElementById('from-unit');
const toUnitEl = document.getElementById('to-unit');
const swapUnitsBtn = document.getElementById('swap-units');
const resultValueEl = document.getElementById('result-value');
const resultUnitEl = document.getElementById('result-unit');
const conversionFormulaEl = document.getElementById('conversion-formula');
const historyListEl = document.getElementById('history-list');
const currencyInfoEl = document.getElementById('currency-info');
const rateUpdateTimeEl = document.getElementById('rate-update-time');

// 单位定义和转换系数
const unitDefinitions = {
    length: {
        units: [
            { id: 'meter', name: '米 (m)' },
            { id: 'kilometer', name: '千米 (km)' },
            { id: 'centimeter', name: '厘米 (cm)' },
            { id: 'millimeter', name: '毫米 (mm)' },
            { id: 'inch', name: '英寸 (in)' },
            { id: 'foot', name: '英尺 (ft)' },
            { id: 'yard', name: '码 (yd)' },
            { id: 'mile', name: '英里 (mi)' }
        ],
        // 转换系数（相对于米）
        factors: {
            meter: 1,
            kilometer: 0.001,
            centimeter: 100,
            millimeter: 1000,
            inch: 39.3701,
            foot: 3.28084,
            yard: 1.09361,
            mile: 0.000621371
        }
    },
    temperature: {
        units: [
            { id: 'celsius', name: '摄氏度 (°C)' },
            { id: 'fahrenheit', name: '华氏度 (°F)' },
            { id: 'kelvin', name: '开尔文 (K)' }
        ],
        // 温度有特殊转换公式，不用简单系数
        specialConversion: true
    },
    weight: {
        units: [
            { id: 'kilogram', name: '千克 (kg)' },
            { id: 'gram', name: '克 (g)' },
            { id: 'milligram', name: '毫克 (mg)' },
            { id: 'metric-ton', name: '吨 (t)' },
            { id: 'pound', name: '磅 (lb)' },
            { id: 'ounce', name: '盎司 (oz)' }
        ],
        // 转换系数（相对于千克）
        factors: {
            kilogram: 1,
            gram: 1000,
            milligram: 1000000,
            metric_ton: 0.001,
            pound: 2.20462,
            ounce: 35.274
        }
    },
    volume: {
        units: [
            { id: 'cubic-meter', name: '立方米 (m³)' },
            { id: 'liter', name: '升 (L)' },
            { id: 'milliliter', name: '毫升 (mL)' },
            { id: 'cubic-centimeter', name: '立方厘米 (cm³)' },
            { id: 'gallon-us', name: '美制加仑 (gal)' },
            { id: 'gallon-uk', name: '英制加仑 (gal)' },
            { id: 'fluid-ounce', name: '液盎司 (fl oz)' },
            { id: 'cubic-inch', name: '立方英寸 (in³)' }
        ],
        // 转换系数（相对于立方米）
        factors: {
            cubic_meter: 1,
            liter: 1000,
            milliliter: 1000000,
            cubic_centimeter: 1000000,
            gallon_us: 264.172,
            gallon_uk: 219.969,
            fluid_ounce: 33814,
            cubic_inch: 61023.7
        }
    },
    currency: {
        units: [
            { id: 'cny', name: '人民币 (CNY)' },
            { id: 'usd', name: '美元 (USD)' },
            { id: 'eur', name: '欧元 (EUR)' },
            { id: 'jpy', name: '日元 (JPY)' },
            { id: 'gbp', name: '英镑 (GBP)' },
            { id: 'aud', name: '澳元 (AUD)' },
            { id: 'cad', name: '加元 (CAD)' }
        ],
        // 模拟汇率数据（相对于CNY）
        rates: {
            cny: 1,
            usd: 0.14,
            eur: 0.13,
            jpy: 20.18,
            gbp: 0.11,
            aud: 0.21,
            cad: 0.18
        },
        lastUpdated: new Date().toLocaleString()
    }
};

// 历史记录
let conversionHistory = [];
const MAX_HISTORY_ITEMS = 10;

// 初始化函数
function initConverter() {
    // 加载保存的历史记录
    loadHistory();
    
    // 初始化单位下拉菜单
    updateUnitDropdowns();
    
    // 执行初始计算
    calculateConversion();
    
    // 添加事件监听器
    conversionCategoryEl.addEventListener('change', handleCategoryChange);
    inputValueEl.addEventListener('input', calculateConversion);
    fromUnitEl.addEventListener('change', calculateConversion);
    toUnitEl.addEventListener('change', calculateConversion);
    swapUnitsBtn.addEventListener('click', swapUnits);
}

// 更新单位下拉菜单
function updateUnitDropdowns() {
    const category = conversionCategoryEl.value;
    const units = unitDefinitions[category].units;
    
    // 清空下拉菜单
    fromUnitEl.innerHTML = '';
    toUnitEl.innerHTML = '';
    
    // 填充下拉菜单
    units.forEach((unit, index) => {
        const fromOption = document.createElement('option');
        fromOption.value = unit.id;
        fromOption.textContent = unit.name;
        fromUnitEl.appendChild(fromOption);
        
        const toOption = document.createElement('option');
        toOption.value = unit.id;
        toOption.textContent = unit.name;
        // 默认选择第二个单位作为目标单位
        if (index === 1) {
            toOption.selected = true;
        }
        toUnitEl.appendChild(toOption);
    });
    
    // 货币类别特殊处理
    if (category === 'currency') {
        currencyInfoEl.style.display = 'block';
        rateUpdateTimeEl.textContent = unitDefinitions.currency.lastUpdated;
    } else {
        currencyInfoEl.style.display = 'none';
    }
}

// 处理类别变化
function handleCategoryChange() {
    updateUnitDropdowns();
    calculateConversion();
}

// 交换单位
function swapUnits() {
    const tempUnit = fromUnitEl.value;
    fromUnitEl.value = toUnitEl.value;
    toUnitEl.value = tempUnit;
    calculateConversion();
}

// 计算转换结果
function calculateConversion() {
    const category = conversionCategoryEl.value;
    const inputValue = parseFloat(inputValueEl.value);
    const fromUnit = fromUnitEl.value;
    const toUnit = toUnitEl.value;
    
    // 验证输入
    if (isNaN(inputValue)) {
        resultValueEl.textContent = '0';
        conversionFormulaEl.textContent = '请输入有效数值';
        return;
    }
    
    let result;
    let formula;
    
    // 执行转换
    if (category === 'temperature') {
        // 温度特殊转换
        result = convertTemperature(inputValue, fromUnit, toUnit);
        formula = getTemperatureFormula(fromUnit, toUnit);
    } else if (category === 'currency') {
        // 货币转换
        result = convertCurrency(inputValue, fromUnit, toUnit);
        formula = getCurrencyFormula(fromUnit, toUnit);
    } else {
        // 使用系数转换
        result = convertWithFactor(inputValue, fromUnit, toUnit, unitDefinitions[category].factors);
        formula = getFactorFormula(fromUnit, toUnit, unitDefinitions[category].factors);
    }
    
    // 更新结果显示
    resultValueEl.textContent = formatNumber(result);
    resultUnitEl.textContent = getUnitDisplayName(category, toUnit);
    conversionFormulaEl.textContent = formula;
    
    // 添加到历史记录
    addToHistory(inputValue, fromUnit, toUnit, result, category);
}

// 使用系数转换（长度、重量、体积）
function convertWithFactor(value, fromUnit, toUnit, factors) {
    // 规范化单位名称（移除连字符）
    const normalizedFromUnit = fromUnit.replace(/-/g, '_');
    const normalizedToUnit = toUnit.replace(/-/g, '_');
    
    // 转换为基准单位，再转换为目标单位
    const baseValue = value / factors[normalizedFromUnit];
    return baseValue * factors[normalizedToUnit];
}

// 温度转换
function convertTemperature(value, fromUnit, toUnit) {
    // 先转换为摄氏度，再转换为目标单位
    let celsius;
    
    switch (fromUnit) {
        case 'celsius':
            celsius = value;
            break;
        case 'fahrenheit':
            celsius = (value - 32) * 5 / 9;
            break;
        case 'kelvin':
            celsius = value - 273.15;
            break;
    }
    
    switch (toUnit) {
        case 'celsius':
            return celsius;
        case 'fahrenheit':
            return celsius * 9 / 5 + 32;
        case 'kelvin':
            return celsius + 273.15;
        default:
            return celsius;
    }
}

// 货币转换
function convertCurrency(value, fromUnit, toUnit) {
    const rates = unitDefinitions.currency.rates;
    // 先转换为CNY，再转换为目标货币
    const cnyValue = value / rates[fromUnit];
    return cnyValue * rates[toUnit];
}

// 获取单位显示名称
function getUnitDisplayName(category, unitId) {
    const units = unitDefinitions[category].units;
    const unit = units.find(u => u.id === unitId);
    return unit ? unit.name.split(' ')[0] : unitId;
}

// 获取系数转换公式
function getFactorFormula(fromUnit, toUnit, factors) {
    const normalizedFromUnit = fromUnit.replace(/-/g, '_');
    const normalizedToUnit = toUnit.replace(/-/g, '_');
    
    const factor = factors[normalizedToUnit] / factors[normalizedFromUnit];
    return `1 ${getUnitDisplayName(conversionCategoryEl.value, fromUnit)} = ${formatNumber(factor)} ${getUnitDisplayName(conversionCategoryEl.value, toUnit)}`;
}

// 获取温度转换公式
function getTemperatureFormula(fromUnit, toUnit) {
    if (fromUnit === toUnit) {
        return `1 ${getUnitDisplayName('temperature', fromUnit)} = 1 ${getUnitDisplayName('temperature', toUnit)}`;
    }
    
    const formulas = {
        'celsius-fahrenheit': '°C 到 °F: (°C × 9/5) + 32',
        'celsius-kelvin': '°C 到 K: °C + 273.15',
        'fahrenheit-celsius': '°F 到 °C: (°F - 32) × 5/9',
        'fahrenheit-kelvin': '°F 到 K: (°F - 32) × 5/9 + 273.15',
        'kelvin-celsius': 'K 到 °C: K - 273.15',
        'kelvin-fahrenheit': 'K 到 °F: (K - 273.15) × 9/5 + 32'
    };
    
    return formulas[`${fromUnit}-${toUnit}`] || '';
}

// 获取货币转换公式
function getCurrencyFormula(fromUnit, toUnit) {
    const rates = unitDefinitions.currency.rates;
    const rate = rates[toUnit] / rates[fromUnit];
    return `1 ${getUnitDisplayName('currency', fromUnit)} = ${formatNumber(rate)} ${getUnitDisplayName('currency', toUnit)}`;
}

// 添加到历史记录
function addToHistory(value, fromUnit, toUnit, result, category) {
    const historyItem = {
        value,
        fromUnit,
        toUnit,
        result,
        category,
        timestamp: new Date().toLocaleString()
    };
    
    // 添加到历史记录开头
    conversionHistory.unshift(historyItem);
    
    // 限制历史记录数量
    if (conversionHistory.length > MAX_HISTORY_ITEMS) {
        conversionHistory.pop();
    }
    
    // 保存并更新显示
    saveHistory();
    updateHistoryDisplay();
}

// 更新历史记录显示
function updateHistoryDisplay() {
    if (conversionHistory.length === 0) {
        historyListEl.innerHTML = '<p class="no-history">暂无转换记录</p>';
        return;
    }
    
    historyListEl.innerHTML = '';
    
    conversionHistory.forEach(item => {
        const historyItemEl = document.createElement('div');
        historyItemEl.className = 'history-item';
        
        historyItemEl.innerHTML = `
            <div>
                <span class="history-value">${formatNumber(item.value)}</span> 
                <span class="history-unit">${getUnitDisplayName(item.category, item.fromUnit)}</span> = 
                <span class="history-value">${formatNumber(item.result)}</span> 
                <span class="history-unit">${getUnitDisplayName(item.category, item.toUnit)}</span>
            </div>
            <div>${item.timestamp}</div>
        `;
        
        historyListEl.appendChild(historyItemEl);
    });
}

// 保存历史记录到本地存储
function saveHistory() {
    localStorage.setItem('conversionHistory', JSON.stringify(conversionHistory));
}

// 从本地存储加载历史记录
function loadHistory() {
    const savedHistory = localStorage.getItem('conversionHistory');
    if (savedHistory) {
        try {
            conversionHistory = JSON.parse(savedHistory);
            updateHistoryDisplay();
        } catch (e) {
            console.error('加载历史记录失败', e);
            conversionHistory = [];
        }
    }
}

// 格式化数字显示
function formatNumber(num) {
    // 对于接近整数的值，显示为整数
    if (Math.abs(num - Math.round(num)) < 1e-10) {
        return Math.round(num).toString();
    }
    
    // 对于小数值，最多显示6位小数
    return num.toFixed(6).replace(/\.?0+$/, '');
}

// 当页面加载完成时初始化
window.addEventListener('DOMContentLoaded', initConverter);